
import math
import os
import json
import time
# 1 1 50+1 10 100 200

Characters_dily_use = {
    "normal" : {
        "carlor_daily": 2600 
    }
}


All_Characters = {
    "heavy_work": {
        "title": "重度劳动者",
        "rate": 1.3,
        "count": 200,
        "wormanRate": 0.3    
    },
    "normal_work": {
        "title": "中度劳动者",
        "rate": 1.15,
        "count": 50,
        "wormanRate": 0.5    
    },
    "solder": {
        "title": "军队",
        "rate": 1.35,
        "count": 51,
        "wormanRate": 0    
    },
    "juexing_chaofan": {
        "title": "超凡觉醒者",
        "rate": 2.5,
        "count": 1,
        "wormanRate": 1    
    },
    "juexing_moli": {
        "title": "魔力觉醒者",
        "rate": 1.15,
        "count": 1,
        "wormanRate": 0    
    },
    "puren": {
        "title": "仆人们",
        "rate": 1.1,
        "count": 10,
        "wormanRate": 0.3    
    },
    "puren": {
        "title": "children",
        "rate": 1.1,
        "count": 50,
        "wormanRate": 0.5   
    },
}

food_template = {
    "black_bread": {
        "title": "黑面包",
        "carlor": 219,
        "weight": 0.2
    },
    "white_bread": {
        "title": "白面包",
        "carlor": 269,
        "weight": 0.2
    },
    "meat_daifei": {
        "title": "腊肉", # 带肥 
        "carlor": 450,
        "weight": 0.1
    },
    "meat_shou": {
        "title": "瘦肉干",  
        "carlor": 160,
        "weight": 0.1
    },
    "fish_gan": {
        "title": "鱼干",  
        "carlor": 110,
        "weight": 0.4
    },
    "food_jiangguo": {
        "title": "浆果",  
        "carlor": 71,
        "weight": 0.2
    },
    "food_vegetable": {
        "title": "蔬菜",  
        "carlor": 45,
        "weight": 0.2
    },
    "food_dou": {
        "title": "豆",  
        "carlor": 172,
        "weight": 0.1
    },
    "food_genjin": {
        "title": "根茎类食物",  
        "carlor": 100,
        "weight": 0.3
    }
}

Items = {
    "xiaomai": {
        "title": "小麦",
        "weight_unit": "kg",
    },
    "maifen": {
        "title": "小麦粉",
        "weight_unit": "kg",
    },
    "heimai": {
        "title": "黑麦",
        "weight_unit": "kg",
    },
    "heimaifen": {
        "title": "黑麦粉",
        "weight_unit": "kg",
    },
    "black_bread": {
        "title": "黑面包",
        "weight_unit": "块"
    },
    "white_bread": {
        "title": "白面包",
        "weight_unit": "块"
    },
}

WorkShops = {
    "mo_fang": {
        "title": "磨坊",
        "count": 1,
        "translate": [
            {
                "use": {
                    "xiaomai": 1,
                },
                "to": {
                    "maifen": 0.75,
                },
                "value": 1
            },
            {
                "use": {
                    "heimai": 1,
                },
                "to": {
                    "heimaifen": 0.75,
                },
                "value": 1
            }
        ],
        "daily_work_speed": 625
    },
    "hong_pei_fang": {
        "title": "烘培坊",
        "count": 2,
        "translate": [
            {
                "use": {
                    "maifen": 0.2,
                    "heimaifen": 1,
                },
                "to": {
                    "black_bread": 5,
                },
                "value": 4
            },
            {
                "use": {
                    "heimaifen": 1,
                },
                "to": {
                    "black_bread": 4,
                },
                "value": 2
            },
            {
                "use": {
                    "maifen": 0.5,
                },
                "to": {
                    "white_bread": 2,
                },
                "value": 1
            }
        ],
        "daily_work_speed": 350,
    }
}

AreaLindi = {
    "money": 6000000,
    "warehouse": {},
}

World_shop = {
    "xiaomai": {
        "price": 238,
        "count": 100
    },
    "heimai": {
        "price": 190,
        "count": 100
    },
    "yan": {
        "price": 400,
        "count": 1
    },
    "tie": {
        "price": 75,
        "count": 1 # 1kg
    },
    "leather": {
        "price": 12,
        "count": 1 # 1kg
    },
    "xiangliao": {
        "price": 1350,
        "count": 1
    },
    "food_vegetable": {
        "price": 300,
        "count": 100
    },
    "food_egg": {
        "price": 5,
        "count": 1
    },
    "meat_daifei": {
        "price": 10,
        "count": 1
    },
    "fish_gan": {
        "price": 40,
        "count": 1
    },
    "black_bread": {
        "price": 2,
        "count": 1
    },
    "white_bread": {
        "price": 4,
        "count": 1
    },
    "armor_tao_ruanjia_leather": {
        "price": 1500,
        "count": 1
    },
    "armor_body_suozijia_iron": {
        "price": 5450,
        "count": 1
    },
    "armor_head_suozijia_iron": {
        "price": 1090,
        "count": 1
    },
    "armor_tao_banjia_iron": {
        "price": 76300,
        "count": 1
    },
    "weapon_sword_iron": {
        "price": 900,
        "count": 1
    },
    "weapon_duanmao_iron": {
        "price": 300,
        "count": 1
    },
    "weapon_mudun_wooden": {
        "price": 100,
        "count": 1
    },
    "cloth_tao_easy": {
        "price": 150,
        "count": 1
    },
    "cloth_tao_good": {
        "price": 450,
        "count": 1
    },
    "animal_cow": {
        "price": 2700,
        "count": 1
    },
    "animal_pig": {
        "price": 900,
        "count": 1
    },
    "animal_sheep": {
        "price": 450,
        "count": 1
    },
    "animal_chicken": {
        "price": 100,
        "count": 1
    },
    "animal_horse": {
        "price": 5400,
        "count": 1
    },
    "animal_warhorse": {
        "price": 44820,
        "count": 1
    },
    "armor_tao_horsearmor_iron": {
        "price": 90000,
        "count": 1
    }
}



Resource = {
    "liechang": {
        "title": "狩猎场",
        "daily": {
            "leather": 15,
            "meat_daifei": 350,
            "meat_shou": 200
        }
    },
    "yuchang": {
        "title": "钓鱼场",
        "daily": {
            "fish_gan": 250,
        }
    },
    "jiangguo": {
        "title": "浆果丛",
        "nowinter": True,
        "daily": {
            "food_jiangguo": 500,
        }
    }
}

ZhongZhi = {
    "xiaomai": {
        "area": 400,
        "maxdays": 365,
        "days": 365,
        "value_area": 800
    },
    "heimai": {
        "area": 400,
        "maxdays": 365,
        "days": 365,
        "value_area": 920
    },
}


dataPath = "./tool/datas"

with open(os.path.join(dataPath,"data.json"), "r") as f:
    AreaLindi = json.load(f)

with open(os.path.join(dataPath,"zhongzhi.json"), "r") as f:
    ZhongZhi = json.load(f)

def save():
    with open(os.path.join(dataPath,"data.json"), "w") as f:
        json.dump(AreaLindi,f,indent=4)
    with open(os.path.join(dataPath,"zhongzhi.json"), "w") as f:
        json.dump(ZhongZhi,f,indent=4)

def calcDailyCarlorUse():
    baseUse = Characters_dily_use["normal"]["carlor_daily"]
    worman_counts = 0
    man_counts = 0
    caruse = 0
    for character_type in All_Characters:
        cinfo = All_Characters[character_type]
        counts = cinfo["count"]
        wormans = round(cinfo["wormanRate"] * counts)
        mans = counts - wormans
        use_car = mans * baseUse * cinfo.get("rate", 1) + wormans * baseUse * cinfo.get("rate", 1) * 0.8
        worman_counts+=wormans
        man_counts+=mans
        caruse+=use_car
        
    return {
        "all": worman_counts + man_counts,
        "worman_counts": worman_counts,
        "man_counts": man_counts,
        "caruse": caruse,
    }


def calcFoodUse(carlorAll) :
    tmp_foods = []
    allCounts = 0
    for food in food_template:
        food_carlor = food_template[food]["weight"]/0.1 * food_template[food]["carlor"]
        if food in AreaLindi["warehouse"]:
            allCounts += AreaLindi["warehouse"][food]
            tmp_foods.append([food,AreaLindi["warehouse"][food], food_carlor])
    tmp_foods.sort(key=lambda v : v[1] * v[2], reverse=True)
    for foodInfo in tmp_foods:
        foodInfo.append(foodInfo[1]/allCounts* 10)
        foodInfo.append(foodInfo[1]/allCounts* 10)
    
    res = {}
    foodusemsg = ""
    while True:
        hasCount = False
        for foodInfo in tmp_foods:
            foodInfo[-1] += foodInfo[-2]
            tuse = int(foodInfo[-1])
            if tuse > 1 and foodInfo[1] > 0:
                if tuse > foodInfo[1]:
                    tuse = foodInfo[1]
                foodInfo[1] -= tuse
                carlorAll -= tuse * foodInfo[2]
                hasCount = True
                foodInfo[-1] -= tuse
        if not hasCount:
            res["not_enough"] = True
            break
        if carlorAll <= 0 :
            break
    for foodinfo in tmp_foods:
        usecound = AreaLindi["warehouse"][foodinfo[0]] - foodinfo[1]
        foodusemsg += f"{food_template[foodinfo[0]]["title"]}:{usecound}\n"
        AreaLindi["warehouse"][foodinfo[0]] = foodinfo[1]
        if AreaLindi["warehouse"][foodinfo[0]] <= 0:
            del AreaLindi["warehouse"][foodinfo[0]]
    res["msg"] = foodusemsg
    return res

def calcWorkShops():
    ret = {

    }
    for workshop in WorkShops:
        workshopInfo = WorkShops[workshop]
        name = workshopInfo["title"]
        allValue = workshopInfo["count"] * workshopInfo["daily_work_speed"]
        workTranslate = workshopInfo["translate"]
        xiaohao = {}
        chanchu = {}
        while allValue > 0 :
            workFlag = False
            for work in workTranslate:
                # 判断use是否足够
                cailiaoFlag = True
                for cailiao in work["use"]:
                    if cailiao in AreaLindi["warehouse"] and AreaLindi["warehouse"][cailiao] > work["use"][cailiao] * work["value"]:
                        pass
                    else :
                        cailiaoFlag = False
                if cailiaoFlag:
                    workFlag = True
                    allValue -= work["value"]
                    for cailiao in work["use"]:
                        AreaLindi["warehouse"][cailiao] -= work["use"][cailiao]*work["value"]
                        if cailiao not in xiaohao: xiaohao[cailiao] = 0
                        xiaohao[cailiao] += work["use"][cailiao]*work["value"]
                        if AreaLindi["warehouse"][cailiao] <= 0 :
                            del AreaLindi["warehouse"][cailiao]
                    for cailiao in work["to"]:
                        if cailiao not in AreaLindi["warehouse"]:
                            AreaLindi["warehouse"][cailiao] = 0
                        AreaLindi["warehouse"][cailiao] += work["to"][cailiao]*work["value"]
                        if cailiao not in chanchu: chanchu[cailiao] = 0
                        chanchu[cailiao] += work["to"][cailiao]*work["value"]

            if not workFlag:
                break
            if allValue <= 0 :
                break



        ret[name] = {
            "xiaohao": xiaohao,
            "chanchu": chanchu,
        } 
    return ret

def calcResource():
    for rtype in Resource:
        if "nowinter" in Resource[rtype] and (AreaLindi["time"]["month"] >= 12 or AreaLindi["time"]["month"] <= 2) :
            continue
        for item in Resource[rtype]["daily"]:
            if item not in AreaLindi["warehouse"] :
                AreaLindi["warehouse"][item] = 0
            AreaLindi["warehouse"][item] += Resource[rtype]["daily"][item]

def calcZhongzhi():
    for item in ZhongZhi:
        info = ZhongZhi[item]
        if info["days"] <= 0 :
            print(item + "丰收!!!!!!!!!!")
            counts = info["area"] * info["value_area"]
            if item not in AreaLindi["warehouse"] :
                AreaLindi["warehouse"][item] = 0
            AreaLindi["warehouse"][item] += counts
            info["days"] = info["maxdays"]
        else:
            info["days"] -= 1

def calcBuySometing() :
    buys = {}
    with open(os.path.join(dataPath,"buys.json"), "r") as f:
        buys = json.load(f)
    all_price = 0
    for item in buys:
        if item in World_shop:
            price_per_count = World_shop[item]["price"]/World_shop[item]["count"]
            price = price_per_count * buys[item]
            all_price += price
            if item not in AreaLindi["warehouse"] :
                AreaLindi["warehouse"][item] = 0
            print(f"购买{item}:{str(buys[item])}")
            AreaLindi["warehouse"][item] += buys[item]
    if all_price > 0 :
        AreaLindi["money"] -= all_price
        print("购买总花费:"+ str(all_price))
        with open(os.path.join(dataPath,"buys.json"), "w") as f:
            json.dump({},f,indent=4)
    
def calcTime():
    if AreaLindi["time"]["days"] >= 30 :
        AreaLindi["time"]["days"] = 0
        if AreaLindi["time"]["month"] >= 12 :
            AreaLindi["time"]["month"] = 1
            AreaLindi["time"]["year"] += 1
        else :
            AreaLindi["time"]["month"] += 1
    else :
        AreaLindi["time"]["days"] += 1

while True:
    AreaLindi["day"] += 1
    calcTime()
    calcBuySometing()
    calcZhongzhi()
    calcResource()
    gongfangret = calcWorkShops()
    for workshopname in gongfangret:
        print(workshopname)
        print(gongfangret[workshopname])

    dailyCarlorUse = calcDailyCarlorUse() # {'all': 353, 'worman_counts': 111, 'man_counts': 242, 'caruse': 1085890.0}
    print("人口:" , dailyCarlorUse["all"])
    fooduse = calcFoodUse(dailyCarlorUse["caruse"])
    print("消耗:")
    print(fooduse["msg"])
    
    

    save()
    print("\n")
    time.sleep(1)
    if "not_enough" in fooduse:
        break
save()

print("end")
